package turtle.system.doug;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

import turtle.system.pt.DailyExec;
import turtle.system.pt.PriceDataForceLossStopProfit;
import arbor.mining.util.date.DateUtil;
import arbor.mining.util.stock.CNYesGather;
import arbor.mining.util.stock.StockEntity;


public class InstantRefineSellExec {

	public static final boolean trainingSVM = false;
    public static final String TrainingDayEnd = "2006/01/01";
    
	public static final String WTX0_PREFIX_FN = "tmp/1000-fake";
	public static final String WTX1_PREFIX_FN = "tmp/WTX1-fake";

	public static final String FN_SUFFIX = ".txt";

	public static final String WTX0_HISTORY_FN = "data/WTX0_history.txt";
	public static final String WTX1_HISTORY_FN = "data/WTX1_history.txt";
	public static final String WTX1_WORD = "WTX1 台指期貨\n\n日期 	開盤 	最高 	最低 	收盤 	成交量\n";
	public static final String WTX0_WORD = "1000 加權\n\n日期 	開盤 	最高 	最低 	收盤 	成交量\n";

	private static final int TYPE_TW1000 = 1;
	private static final int TYPE_TWX1 = 2;
	Properties urlProp;

	private void setupURLProperties() {
		urlProp = new Properties();
		try {
			urlProp
					.load(InstantRefineSellExec.class.getClassLoader()
							.getResourceAsStream(
									"turtle/system/pt/stock.properties"));
		} catch (IOException e) {
			System.out.println(e);
		}
	}


	public InstantRefineSellExec() throws IOException {
		setupURLProperties();
			DateFormat df = new SimpleDateFormat("yyyyMMdd");
			Date today = DateUtil.getCurrentDate();

			CNYesGather gather = new CNYesGather();
			StockEntity[] wtx = gather.getInstantWTXPrice();
			
			this.copyFile(DailyExec.WTX0_PREFIX_FN+DailyExec.FN_SUFFIX, WTX0_PREFIX_FN+FN_SUFFIX);
			this.copyFile(DailyExec.WTX1_PREFIX_FN+DailyExec.FN_SUFFIX, WTX1_PREFIX_FN+FN_SUFFIX);
			String fn;
			/**
			 * 改為wtx[2],如果要測試隔月資料
			 */
			if (wtx[1]!=null) {
			  fn = WTX1_PREFIX_FN+FN_SUFFIX;
			  dailySave2File(wtx[1], fn, TYPE_TWX1);
			}
			if (wtx[0]!=null) { 
			  fn = WTX0_PREFIX_FN+FN_SUFFIX;
			  dailySave2File(wtx[0], fn, TYPE_TW1000);
			}
		
		PriceDataRefineSellSystem cons = new PriceDataRefineSellSystem(PriceDataForceLossStopProfit.STRATEGY_CONSERVATIVE,
				InstantRefineSellExec.WTX0_PREFIX_FN + InstantRefineSellExec.FN_SUFFIX,
				InstantRefineSellExec.WTX1_PREFIX_FN + InstantRefineSellExec.FN_SUFFIX);
	}

	private static void copyFile(String srcFN, String destFN) {
		try {
			File inputFile = new File(srcFN);
			File outputFile = new File(destFN);

			FileReader in = new FileReader(inputFile);
			FileWriter out = new FileWriter(outputFile);
			int c;

			while ((c = in.read()) != -1)
				out.write(c);

			in.close();
			out.close();
		} catch (IOException e) {
			System.out.println(e);
		}
	}

	private void dailySave2File(StockEntity entity, String fileName, int type) {
		DateFormat df = new SimpleDateFormat("yyyy/MM/dd");

		ArrayList<String> dayList1 = new ArrayList<String>();
		ArrayList<String> dayList = new ArrayList<String>();
		Date trainEnd = null;
		try {
			if (trainingSVM)
			  trainEnd = df.parse(TrainingDayEnd);
			else
			  trainEnd = Calendar.getInstance().getTime();
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			BufferedReader reader = new BufferedReader(new FileReader(fileName));
			reader.readLine();
			reader.readLine();
			reader.readLine();
			String line;
			while ((line = reader.readLine()) != null) {
				dayList1.add(line);
			}

			reader.close();
			
			/**
			 * The least day is a fake entity.
			 */
            for (int i=0;i<dayList1.size()-1;i++) {
				line = dayList1.get(i);
				String d = line.split(" 	")[0];				  
				  if (df.parse(d).compareTo(
						df.parse(DateUtil.getCurrentSlashDate())) < 0) {
					  if (df.parse(d).before(trainEnd)){
					    dayList.add(line);
					  }
					  else {
					   //System.out.println(d);
					  }

				  } else {
					 //System.out.println(d);
				  }			
				
			}
			
			BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
			StringBuffer buf = new StringBuffer();
			switch (type) {
			case TYPE_TW1000:
				writer.write(WTX0_WORD);
				break;
			case TYPE_TWX1:
				writer.write(WTX1_WORD);
				break;
			}
			for (int i = 0; i < dayList.size(); i++) {
				writer.write(dayList.get(i) + "\n");
			}

if (!trainingSVM) {			
			String d = df.format(entity.startTime.getTime());

			Date tomorrow = DateUtil.getDaysAfterToday(1);
			buf.append(df.format(tomorrow) + " 	");
			buf.append(entity.ohlc.open + " 	");
			buf.append(entity.ohlc.high + " 	");
			buf.append(entity.ohlc.low + " 	");
			buf.append(entity.ohlc.close + " 	");
			buf.append(entity.volume + "\n");

			writer.write(df.format(entity.startTime.getTime()) + " 	");
			writer.write(entity.ohlc.open + " 	");
			writer.write(entity.ohlc.high + " 	");
			writer.write(entity.ohlc.low + " 	");
			writer.write(entity.ohlc.close + " 	");
			writer.write(entity.volume + "\n");

			writer.write(buf.toString());
}
			writer.flush();
			writer.close();
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	private void historySave2File(ArrayList<StockEntity> entities,
			String fileName, int type) {

		DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
			switch (type) {
			case TYPE_TW1000:
				writer.write(WTX0_WORD);
				break;
			case TYPE_TWX1:
				writer.write(WTX1_WORD);
				break;
			}
			StringBuffer buf = new StringBuffer();
			for (int i = 0; i < entities.size(); i++) {
				StockEntity entity = entities.get(i);
				String d = df.format(entity.startTime.getTime());
				if (i == entities.size() - 1) {
					Date tomorrow = DateUtil.getDaysAfterToday(1);
					buf.append(df.format(tomorrow) + " 	");
					buf.append(entity.ohlc.open + " 	");
					buf.append(entity.ohlc.high + " 	");
					buf.append(entity.ohlc.low + " 	");
					buf.append(entity.ohlc.close + " 	");
					buf.append(entity.volume + "\n");
				}
				writer.write(df.format(entity.startTime.getTime()) + " 	");
				writer.write(entity.ohlc.open + " 	");
				writer.write(entity.ohlc.high + " 	");
				writer.write(entity.ohlc.low + " 	");
				writer.write(entity.ohlc.close + " 	");
				writer.write(entity.volume + "\n");
			}
			writer.flush();
			writer.close();
		} catch (IOException e) {
			System.out.println(e);
		}
	}
	public static void main(String[] args) throws IOException {
			new InstantRefineSellExec();

	}

}